package com.foreknow.controller;

import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;
import com.foreknow.model.Guestbook;
import com.foreknow.service.GuestbookService;
import com.foreknow.service.impl.GuestbookServiceImpl;
import com.foreknow.util.Pagination;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author shkstart
 * @create 2021-08-23 14:39
 */
public class ManagerServlet extends HttpServlet {
    private int pageSize = 10;

    @Override
    public void init(ServletConfig config) throws ServletException {
        String spageSize = config.getServletContext().getInitParameter("pageSize");
        this.pageSize = Integer.parseInt(spageSize);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        获取请求参数
        String method = req.getParameter("q");
        if ("delete".equals(method)) {
            delete(req, resp);
        } else if ("getQueryById".equals(method)) {
            getQueryById(req, resp);
        } else if ("update".equals(method)) {
            update(req, resp);
        } else if ("save".equals(method)) {
            save(req, resp);
        } else {
            list(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);

    }

    /**
     * 查询所有留言信息
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();//
        GuestbookService service = new GuestbookServiceImpl();
//        List<Object> list = service.showAll();
        int pagenumber = 1;
        Pagination pagination = service.getByPage(pageSize, pagenumber);
        MappingFactory mappingFactory = MappingFactory.getInstance();
        EntityMapping map = mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list = pagination.getList(map);

        //要将list集合在服务器端保存起来(后期就可以在页面中获取到list集合)
        req.setAttribute("list", list);

        HttpSession session = req.getSession();

        session.setAttribute("list", list);

        //将总记录数存到session中
        int maxElements = pagination.getMaxElements();
        session.setAttribute("total", maxElements);

        //将资源转发到list.jsp中
        // req.getRequestDispatcher("/list.jsp").forward(req, resp);
        //重定向 必须将req请求参数放到session中  否则直接重定向没有参数  页面不显示
        resp.sendRedirect(req.getContextPath() + "/list.jsp");
    }

    /**
     * 根据id删除留言信息
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();//
        GuestbookServiceImpl service = new GuestbookServiceImpl();
        String sid = req.getParameter("id");
        int id = Integer.parseInt(sid);

        boolean b = service.deleteById(id);
        if (b) {
            list(req, resp);
        } else {
            out.println("<script>alert('此数据不存在')</script>");
        }


    }

    /**
     * 修改留言信息
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        Guestbook queryById = (Guestbook) session.getAttribute("queryById");
//        int id=queryById.getId();
//        String name=queryById.getName();
//        String phone=queryById.getPhone();
//        String email=queryById.getEmail();
//        String title=queryById.getTitle();
//        String content=queryById.getContent();


        //获取jsp页面提交的内容
        String sid = req.getParameter("id");
        int id = Integer.parseInt(sid);
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        // String createdtime = req.getParameter("createdtime");

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String createdtime = simpleDateFormat.format(date);
        //将获取修改的内容封装到对象中
        Guestbook gb = new Guestbook(id, name, phone, email, title, content, createdtime);
        GuestbookServiceImpl service = new GuestbookServiceImpl();

        //调用update()方法 更新数据库数据
        req.getSession().setAttribute("queryById", gb);
        boolean update = service.update(gb);


        if (update) {
            list(req, resp);
        }

//        Object queryById = req.getAttribute("queryById");


//        boolean b = service.updateById((Guestbook) gb);

    }

    /**
     * 根据id查
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void getQueryById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        GuestbookServiceImpl service = new GuestbookServiceImpl();
        String uid = req.getParameter("uid");
        int id = Integer.parseInt(uid);
        Guestbook queryById = service.getQueryById(id);
        HttpSession session = req.getSession();
        if (queryById != null) {
//            req.setAttribute("queryById",queryById);
            session.setAttribute("queryById", queryById);
            req.getRequestDispatcher("/update.jsp").forward(req, resp);
//            resp.sendRedirect(req.getContextPath()+"/update.jsp");
        }
    }

    /**
     * 添加数据
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        //获取请求参数
        String username = req.getParameter("name");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        Date date = new Date();

//获取年月日时分秒，也可以只获取其中的一个，其中的中文汉字可以改为-
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
//SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createdTime = formatter.format(date);

        GuestbookService guestbookService = new GuestbookServiceImpl();


        Guestbook guestbook = new Guestbook(username, phone, email, title, content, createdTime);

        boolean add = guestbookService.add(guestbook);
        if (add) {
//            out.println("添加成功");
            //超链接必须加Application context
//            out.println("<a href='/ManagerSystem/show'>查看所有留言</a>");
//            //如果添加成功了直接转发资源     请求转发
//            RequestDispatcher rd = req.getRequestDispatcher("/user/manager");
//            rd.forward(req,resp);
            list(req, resp);
//            req.getRequestDispatcher("/show").forward(req,resp);
            //重定向
//            req.getContextPath();  //获取到工程名路径
//            resp.sendRedirect(req.getContextPath()+"/show");    //站内资源
//                resp.sendRedirect("");
        } else {
            out.println("添加失败");
        }
    }


}
